package com.WOWTradeNews.phone;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.TreeSet;

import javax.crypto.interfaces.PBEKey;

import android.app.Activity;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Resources.Theme;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.WOWTradeNewsTest.R;
import com.WOWTradeNews.Utils;
import com.WOWTradeNews.DataBase.ConstValues;
import com.WOWTradeNews.DataBase.DBManager;
import com.WOWTradeNews.DataBase.News;
import com.WOWTradeNews.DataBase.NewsDataBase;
import com.WOWTradeNews.DataBase.SystemDBManager;
import com.WOWTradeNews.Util.Wether;
import com.WOWTradeNews.services.AD;
import com.WOWTradeNews.services.NewsServer;

public class TradeNewsList extends Activity implements Runnable{

	//private NewsDataBase database;
	//private Cursor myCursor;
	private ListView myListView;
	private String newsId, type, subject;
	
	private ImageView refreshImageView;
	private ProgressDialog pd;
	
	private Button backButton;
	
	private DBManager dbManager;
	private SystemDBManager systemDBManager;

	private List<News> items;
	private int newsType;

	protected static final int MENU_CATEGORY_EXHIBITOR = Menu.FIRST + 1;
	protected static final int MENU_SECRECT_EVENTS = Menu.FIRST + 2;
	protected static final int MENU_TICA_BONUS = Menu.FIRST + 3;
	protected static final int MENU_DIGEST = Menu.FIRST + 4;
	protected static final int MENU_FLOOR_PLAN = Menu.FIRST + 5;

	protected TextView topSubject;
	
	private List<News> adList;
	private List<News> finalList;
//	private TreeSet mSet = new TreeSet();
	
	private NewsListAdapter myAdapter;
	String search = "";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.market_research_phone);
		new Wether().execute();
		Bundle bundle = this.getIntent().getExtras();
		if (bundle != null) {
			type = bundle.getString("type");
			subject = bundle.getString("subject");
			search = bundle.getString("search");
		}
		System.out.println("newsType:"+type);
		newsType = Integer.parseInt(type);
		
		
		myListView = (ListView) findViewById(R.id.list_view);
		topSubject = (TextView) findViewById(R.id.subject);
		backButton = (Button) findViewById(R.id.back);
		topSubject.setText(subject);
		backButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		refreshImageView = (ImageView) findViewById(R.id.refresh);
		if(search != null && search.equals("yes")) refreshImageView.setVisibility(View.GONE);
		refreshImageView.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(!Utils.isConnect(TradeNewsList.this)) {
					Dialog.showDialog(TradeNewsList.this, "目前為無網路狀態");
					return;
				}
				pd = new ProgressDialog(TradeNewsList.this);
				pd.setMessage("下載中...");
				pd.setCanceledOnTouchOutside(false);
				pd.show();
				new Thread(TradeNewsList.this).start();
			}
		});
		
		dbManager = new DBManager(TradeNewsList.this, ConstValues.DB_NEWS);
		systemDBManager = new SystemDBManager(TradeNewsList.this);
		
		//get ad list
		adList = dbManager.getNewsList(ConstValues.NEWS_TYPE_AD);

		try{
			
			//添加广告list
			//finalList = getFinalList(items, adList);
			myAdapter = null;
			if(newsType < 6) {
				TreeSet set = new TreeSet();
				List<News> newsList = dbManager.getNewsList(newsType+1);
				finalList = getFinalList(newsList, adList,set);
				if(finalList == null || finalList.size() == 0) {
					Toast.makeText(TradeNewsList.this, "目前無資料,請按\"重新整理\"下載", Toast.LENGTH_LONG).show();
				}
				myAdapter = new NewsListAdapter(this,finalList,myListView,newsType, set);
			} else if(newsType == 6) {	//favorites
				/*List<News> favoritesList = systemDBManager.getMyFavoritesList();
				if(favoritesList == null || favoritesList.size() == 0) {
					Toast.makeText(TradeNewsList.this, "查無資料", Toast.LENGTH_LONG).show();
				}
				TreeSet set = new TreeSet();
				myAdapter = new NewsListAdapter(this, favoritesList, myListView, 1, set);
				refreshImageView.setEnabled(false);
				refreshImageView.setVisibility(ImageView.INVISIBLE);*/
				
				finalList = systemDBManager.getMyFavoritesList();
				if(finalList == null || finalList.size() == 0) {
					Toast.makeText(TradeNewsList.this, "目前無資料", Toast.LENGTH_LONG).show();
				}
				TreeSet set = new TreeSet();
				myAdapter = new NewsListAdapter(this, finalList, myListView, 1, set,true);
				refreshImageView.setEnabled(false);
				refreshImageView.setVisibility(View.GONE);
			} else if(newsType == 8) {	//相關活動
				Bundle bundle2 = TradeNewsList.this.getIntent().getExtras();
				String country = bundle2.getString("countryName");
				finalList = dbManager.getNewsByCountry(country);
				if(finalList == null || finalList.size() == 0) {
					Toast.makeText(TradeNewsList.this, "目前無資料", Toast.LENGTH_LONG).show();
				}
				TreeSet set = new TreeSet();
				myAdapter = new NewsListAdapter(this, finalList, myListView, 1, set);
				refreshImageView.setEnabled(false);
				refreshImageView.setVisibility(View.GONE);
			} else if(newsType == 11) {
				Map<String, String> map = new HashMap<String, String>();
				Bundle b = TradeNewsList.this.getIntent().getExtras();
				//"theme", "keywords", "s_keywords", "country", "city" ,"date1", "date2", "search"
				map.put("theme", b.getString("theme"));
				map.put("keywords", b.getString("keywords"));
				map.put("s_keywords", b.getString("s_keywords"));
				map.put("country", b.getString("country"));
				map.put("city", b.getString("city"));
				map.put("date1", b.getString("date1"));
				map.put("date2", b.getString("date2"));
				map.put("search", b.getString("search"));
				
				finalList = NewsServer.searchList(map);
				if(finalList == null || finalList.size() == 0) {
					Toast.makeText(TradeNewsList.this, "目前無資料", Toast.LENGTH_LONG).show();
				} else {
					int nowCoin = systemDBManager.getMyCoin();
					if(nowCoin >= 3) {
						systemDBManager.setMyCoin(nowCoin - 3);
					} else {
						systemDBManager.setMyCoin(nowCoin);
					}
				}
				TreeSet set = new TreeSet();
				myAdapter = new NewsListAdapter(this, finalList, myListView, 1, set);
				refreshImageView.setEnabled(false);
				refreshImageView.setVisibility(View.GONE);
				Log.d("zhaosdfa", "invisible");
			}
			myListView.setAdapter(myAdapter);
			myListView.setOnItemClickListener(new OnItemClickListener() {
	
				@Override
				public void onItemClick(AdapterView<?> arg0, View view, int position,long arg3) {
					int type = myAdapter.getItemViewType(position);
					News news = finalList.get(position);
					if(!news.isGj()) {
						if(type == NewsListAdapter.VIEW_TYPE_NEWS) {
							newsId = ((TextView) view.findViewById(R.id.ItemID)).getText().toString();
							
							Intent intent = new Intent();
							intent.setClass(TradeNewsList.this, NewsDetail.class);
			
							//intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							Bundle bundle = new Bundle();
							//bundle.putString("newsID", newsId);
							bundle.putString("subject", subject);
							
							bundle.putParcelable("news", news);
							bundle.putInt("newsType", newsType);
			
							intent.putExtras(bundle);
							startActivity(intent);
						} else {
							String url = ((TextView)view.findViewById(R.id.ad_item_url)).getText().toString();
							//Toast.makeText(TradeNewsList.this, url, 0).show();
							if(url != null) {
								/*Uri uri = Uri.parse(url);  
								Log.d("zhaosdfa", "url:" + uri);
								Intent it = new Intent(Intent.ACTION_VIEW, uri);  
								startActivity(it);*/
								Intent intent_url = new Intent(TradeNewsList.this, PreferentialActivity.class);
								intent_url.putExtra("url", url);
								startActivity(intent_url);
							}
						}
					} else {
						Intent intent = new Intent(TradeNewsList.this, ReCountryDetail.class);
						Bundle bundle = new Bundle();
						bundle.putString("content", news.getGjContent());
						bundle.putString("title", news.getGjtitle());
						intent.putExtras(bundle);
						startActivity(intent);
					}
					
				}
			});
		}
		catch(Exception e){
			Toast.makeText(TradeNewsList.this, "目前無資料,請按\"重新整理\"下載", Toast.LENGTH_LONG).show();
			Log.e("onCreate", e.toString());
		}
		finally{
			//if(!myCursor.isClosed()) myCursor.close();
			//database.close();
			
		}
		
	}

	/**
	 * 
	 * @param items
	 * @param adList
	 * @return
	 */
	private List<News> getFinalList(List<News> items, List<News> adList,TreeSet set) {
		List<News> res = new ArrayList<News>();
		int cnt, adcnt;
		Iterator<News> it = adList.iterator();
		
		cnt = 0;
		adcnt = 0;
		
		Random random = new Random();
		int tt = random.nextInt(4);
		tt += 2;
		for(News n : items) {
			res.add(n);
			
			//Log.d("zhaosdfa", "tt:" + tt);
			if(++cnt == tt && it.hasNext()) {
				News t = it.next();
				res.add(t);
				set.add(res.size()-1);
				cnt = 0;
				tt = random.nextInt(4);
				tt += 2;
			}
		}
		
		return res;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, MENU_CATEGORY_EXHIBITOR, 1, "活動快訊");
		menu.add(0, MENU_SECRECT_EVENTS, 2, "商情放送");
		menu.add(0, MENU_TICA_BONUS, 3, "專題研析");
		menu.add(0, MENU_DIGEST, 4, "市調精華");
		menu.add(0, MENU_FLOOR_PLAN, 5, "經貿書訊");

		return super.onCreateOptionsMenu(menu);
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		Bundle bundle = new Bundle();

		switch (item.getItemId()) {
		case MENU_CATEGORY_EXHIBITOR:
			bundle.putString("type", "4");
			bundle.putString("subject", "活動快訊");
			startActivity(new Intent(TradeNewsList.this, TradeNewsList.class).putExtras(bundle));
			break;
		case MENU_SECRECT_EVENTS:
			bundle.putString("type", "3");
			bundle.putString("subject", "商情放送");
			startActivity(new Intent(TradeNewsList.this, TradeNewsList.class).putExtras(bundle));
			break;
		case MENU_TICA_BONUS:
			bundle.putString("type", "2");
			bundle.putString("subject", "專題研析");
			startActivity(new Intent(TradeNewsList.this, TradeNewsList.class).putExtras(bundle));
			break;
		case MENU_DIGEST:
			bundle.putString("type", "1");
			bundle.putString("subject", "市調精華");
			startActivity(new Intent(TradeNewsList.this, TradeNewsList.class).putExtras(bundle));
			break;
		case MENU_FLOOR_PLAN:
			bundle.putString("type", "5");
			bundle.putString("subject", "經貿書訊");
			startActivity(new Intent(TradeNewsList.this, TradeNewsList.class).putExtras(bundle));
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	private int getItemViewType(int position,TreeSet set) {
        return set.contains(position) ? NewsListAdapter.VIEW_TYPE_AD : NewsListAdapter.VIEW_TYPE_NEWS;
    }
	
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			pd.dismiss();
			myAdapter = null;
			adList = dbManager.getNewsList(ConstValues.NEWS_TYPE_AD);
			if(newsType < 6) {
				TreeSet set = new TreeSet();
				List<News> newsList = dbManager.getNewsList(newsType+1);
				finalList = getFinalList(newsList, adList,set);
				myAdapter = new NewsListAdapter(TradeNewsList.this,finalList,myListView,newsType, set);
			} else if(newsType == 6) {	//favorites
				List<News> favoritesList = systemDBManager.getMyFavoritesList();
				
				TreeSet set = new TreeSet();
				myAdapter = new NewsListAdapter(TradeNewsList.this, favoritesList, myListView, 1, set);
				refreshImageView.setEnabled(false);
				refreshImageView.setVisibility(ImageView.INVISIBLE);
			} else if(newsType == 8) {	//相關活動
				Bundle bundle2 = TradeNewsList.this.getIntent().getExtras();
				String country = bundle2.getString("countryName");
				List<News> acticList = dbManager.getNewsByCountry(country);
				TreeSet set = new TreeSet();
				myAdapter = new NewsListAdapter(TradeNewsList.this, acticList, myListView, 1, set);
				refreshImageView.setEnabled(false);
				refreshImageView.setVisibility(ImageView.INVISIBLE);
			}
			myListView.setAdapter(myAdapter);
			myListView.setAdapter(myAdapter);
			//myAdapter.notifyDataSetChanged();
			//Toast.makeText(TradeNewsList.this, "test", 0).show();
		}
	};

	List<News> list_;
	List<News> adList_;
	public void run() {
		int newsType = Integer.parseInt(type) + 1;
		try {
			Log.d("zhaosdfa", "newsType:" + newsType);
			list_ = NewsServer.getNewsList(newsType);
			dbManager.deleteByType(newsType);
			if(list_ != null && list_.size() > 0) {
				//dbManager.deleteTypeNews(newsType);
				//dbManager.addNews(list);
				TreeSet<String> set = new TreeSet<String>();
				for(News n : list_) {
					dbManager.addNews(n);
					/*String iid = n.getIid();
					set.add(iid);
					if(dbManager.findByIid(iid) == null) {
						if(n.getImg1Url() != null && !n.getImg1Url().equals("")) {
							n.setImg(Utils.getUrlBitmapBonus(n.getImg1Url()));
						}
						dbManager.addNews(n);
					} else {
						dbManager.deleteByIid(iid);
						dbManager.addNews(n);
					}*/
				}
//				dbManager.deleteTypeOthers(set, newsType);
			}
			adList_ = AD.getAdList();
			if(adList != null && adList.size() > 0)dbManager.deleteTypeNews(ConstValues.NEWS_TYPE_AD);
			dbManager.addNews(adList);
		} catch (Exception e) {
			e.printStackTrace();
		}
//		handler.sendEmptyMessage(0);
		h.sendEmptyMessage(0);
	}
	
	
	Handler h = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			pd.dismiss();
			if(newsType < 6) {
				TreeSet set = new TreeSet();
				finalList = getFinalList(list_, adList_,set);
//				myAdapter = new NewsListAdapter(TradeNewsList.this,finalList,myListView,newsType, set);
			} else if(newsType == 6) {	//favorites
				List<News> favoritesList = systemDBManager.getMyFavoritesList();
				
				TreeSet set = new TreeSet();
				myAdapter = new NewsListAdapter(TradeNewsList.this, favoritesList, myListView, 1, set);
				refreshImageView.setEnabled(false);
				refreshImageView.setVisibility(ImageView.INVISIBLE);
			} else if(newsType == 8) {	//相關活動
				Bundle bundle2 = TradeNewsList.this.getIntent().getExtras();
				String country = bundle2.getString("countryName");
				List<News> acticList = dbManager.getNewsByCountry(country);
				TreeSet set = new TreeSet();
				myAdapter = new NewsListAdapter(TradeNewsList.this, acticList, myListView, 1, set);
				refreshImageView.setEnabled(false);
				refreshImageView.setVisibility(ImageView.INVISIBLE);
			}
//			myListView.setAdapter(myAdapter);
			myAdapter.notifyDataSetChanged();
			super.handleMessage(msg);
		}
		
	};
	
	@Override
	public void onDestroy() {
		dbManager.closeDB();
		super.onDestroy();
	}
	
}
